app.controller('AdsListCtrl', function ($scope, ajax, $modal, toaster) {

	var inserter = new Req.POST({ resource: $scope.resource });
	var deleter = new Req.DELETE({ resource: $scope.resource });
	var updater = new Req.PUT({ resource: $scope.resource });

	$scope.reload = $scope.page.loader('ads/{pageIndex}/{pageSize}/page');
	$scope.$on('pageIndex', function (event, p) { $scope.reload(p, $scope.queryMap); });
	$scope.reload(1);
	$scope.queryMap = {};
	$scope.query = function () { $scope.reload(1, $scope.queryMap); };

	// 新增、更新
	$scope.write = function (size, current_data, submit_type) {
		$scope.current_data = angular.copy(current_data);
		var modalInstance = $modal.open({
			templateUrl: 'template/system/ads/writeModal.html?v=904f43b808',
			controller: 'AdsModalCtrl',
			size: size,
			resolve: {
				param: function () {
					return {
						"data": $scope.current_data,
						"type": submit_type
					};
				}
			}
		});

		modalInstance.result.then(function (param) {
			if (param.type == 'update') {
				updater.fields = param.data;
				updater.id = param.data.id;
				updater.resource = 'ads/update';
				$scope.page.mod(updater, $scope.reload, $scope.queryMap);
			} else if (param.type == 'insert') {
				inserter.fields = param.data;
				inserter.resource = 'ads/insert';
				$scope.page.add(inserter, $scope.reload, $scope.queryMap);
			}
		});
	};

	$scope.ids = [];
	$scope.checks = false;//默认未选中
	$scope.ckAll = false;//默认未选中
	$scope.choseArr = [];

	/*单选*/
	$scope.check = function (val) {
		if ($scope.ids.indexOf(val) < 0) {
			$scope.ids.push(val);
		} else {
			$scope.ids.splice($scope.ids.indexOf(val), 1);
		}
	};

	/*全选*/
	$scope.checkAll = function (c, v) {
		if (c == true) {
			$scope.checks = true;
			$scope.choseArr = v;
			//添加所选Id
			for (var i = 0; i < $scope.choseArr.length; i++) {
				$scope.ids.push($scope.choseArr[i].id);
			}
		} else {
			$scope.checks = false;
			$scope.ids = [];
		}
	};

	//删除
	$scope.del = function (size, current_data, submit_type) {
		var modalInstance = $scope.delModal(size, current_data, submit_type);
		modalInstance.result.then(function (param) {
			if (param.type == 'delete') {
				deleter.id = param.data.id;
				deleter.resource = 'ads/' + deleter.id + '/delete';
				$scope.page.del(deleter, $scope.reload, $scope.queryMap);
			} else if (param.type == 'deleteAll') {
				if ($scope.ids == "" || $scope.ids == null) {
					toaster.pop('warning', '提示', '请至少选择一条要删除的信息！');
				} else {
					deleter.datalist = $scope.ids;
					deleter.resource = 'ads/batch/delete';
					ajax.call(deleter).then(function (result) {

						if (result.code == 200) {
							toaster.pop('success', '成功', '删除信息成功。');
							$scope.reload(1, $scope.queryMap);
							$scope.ids = null;
						} else {
							toaster.pop('error', '错误', '删除信息失败！');
						}
					}, function () { toaster.pop('error', '错误', '删除信息失败！'); });
				}
			}
		});
	};

});
